package rlyy.framework.core.servlet;

import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.server.AbstractServletWebServerFactory;

import javax.servlet.ServletContext;

/**
 * @author yuanqinglong
 * @since 2021/4/12 14:59
 */
public class InitServletContextServer extends AbstractServletWebServerFactory {


    /**
     * 默认是个空的webServer 什么都不做、兼容springboot2.3启动报错
     * 启动nettyServer会通过构造覆盖调空的webServer
     */
    private WebServer webServer = new EmptyWebServer();

    /**
     * 不启动netty时、spring初始化时调用空构造创建此对象
     */
    public InitServletContextServer() {
    }

    /**
     * 启动nettyServer时，netty-starter会拦截Spring创建此对象流程、通过有参构造创建此对象 覆盖默认的空服务
     *
     * @param webServer nettyServer
     */
    public InitServletContextServer(WebServer webServer) {
        this.webServer = webServer;
    }


    @Override
    public WebServer getWebServer(ServletContextInitializer... initializers) {
        ServletContext servletContext = new MyServletContext();
        try {
            for (ServletContextInitializer initializer : super.mergeInitializers(initializers)) {
                initializer.onStartup(servletContext);
            }
            return webServer;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}
